const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const localVideo = document.getElementById('localVideo');

let localStream;
let peerConnection;
let socket;

const servers = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' }
    ]
};

function start() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(stream => {
            localStream = stream;
            localVideo.srcObject = stream;

            createPeerConnection();

            startButton.disabled = true;
            stopButton.disabled = false;
        })
        .catch(error => {
            console.error('Error accessing media devices.', error);
        });
}

function stop() {
    if (localStream) {
        localStream.getTracks().forEach(track => track.stop());
    }

    if (peerConnection) {
        peerConnection.close();
        peerConnection = null;
    }

    if (socket) {
        socket.close();
        socket = null;
    }

    localVideo.srcObject = null;

    startButton.disabled = false;
    stopButton.disabled = true;
}

function createPeerConnection() {
    peerConnection = new RTCPeerConnection(servers);

    peerConnection.addStream(localStream);

    peerConnection.onicecandidate = handleIceCandidate;

    createOffer();
}

function createOffer() {
    peerConnection.createOffer()
        .then(offer => peerConnection.setLocalDescription(offer))
        .then(() => sendSignalingMessage(peerConnection.localDescription))
        .catch(error => console.error('Error creating offer:', error));
}

function handleIceCandidate(event) {
    if (event.candidate) {
        sendSignalingMessage({ type: 'candidate', candidate: event.candidate });
    }
}

function sendSignalingMessage(message) {
    console.log("Sending signaling message:", message);
    if (!socket) {
        socket = new WebSocket('wss://192.168.2.46:8080/websocket');
        socket.onopen = () => {
            console.log('WebSocket connection established');
            socket.send(JSON.stringify(message));
        };
        socket.onmessage = event => {
            const data = JSON.parse(event.data);
            console.log('Received message:', data);
            if (data.type === 'answer') {
                peerConnection.setRemoteDescription(new RTCSessionDescription(data))
                    .catch(error => console.error('Error setting remote description:', error));
            } else if (data.type === 'candidate') {
                peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                    .catch(error => console.error('Error adding ICE candidate:', error));
            }
        };
        socket.onerror = error => {
            console.error('WebSocket error:', error);
        };
        socket.onclose = () => {
            console.log('WebSocket connection closed');
            socket = null;
        };
    } else {
        if (socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket is not open. Ready state:', socket.readyState);
        }
    }
}

startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);